using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Geekeradmin.Authorize;
using Geekeradmin.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Options;
using MySqlX.XDevAPI.Common;
using Publicuse.Appication;
using Publicuse.Autofac;
using Publicuse.Entity;
using Publicuse.Entity.AttributeUtil;
using Publicuse.Export;
using Publicuse.Interface;
using Publicuse.Interface.Extend;
using Publicuse.Util;

namespace Geekeradmin.Controllers
{
  /// <summary>
  /// 日志管理
  /// </summary>
  [UserAuthorize("Admin")]
  public class LogController : BaseController
  {
    public LogController(
      IAutofaceInstance autoface,
      IMySqlSugarService mySqlSugar,
      IWebHostEnvironment webHost,
      IOptions<DBConnectionOption> options,
      IBaseServiceExt baseServiceExt
    )
      : base(autoface, mySqlSugar, webHost, options, baseServiceExt) { }

    /// <summary>
    /// 获取系统所有模块
    /// </summary>
    /// <returns></returns>
    [HttpGet("GetList"), AllowAnonymous]
    public async Task<JsonResult> GetList()
    {
      CommonResult result = await LogApplication.GetApplication(container).GetList();
      return new JsonResult(result);
    }

    /// <summary>
    /// 获取日志信息列表（功能操作统计模式）
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpPost("GetLista")]
    public async Task<JsonResult> GetLista(Log query)
    {
      query.loginUserCode = HttpContextExtendBase.GetLoginCode();
      CommonResult result = await LogApplication.GetApplication(container).GetLista(query);
      return new JsonResult(result);
    }

    /// <summary>
    /// 获取日志信息列表(控制器统计模式)
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpPost("GetListb")]
    public async Task<JsonResult> GetListb(Controllerexelog query)
    {
      query.loginUserCode = HttpContextExtendBase.GetLoginCode();
      CommonResult result = await LogApplication.GetApplication(container).GetListb(query);
      return new JsonResult(result);
    }

    /// <summary>
    /// 获取日志信息列表(账号登录统计模式)
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpPost("GetListc")]
    public async Task<JsonResult> GetListc(SigninInfo query)
    {
      query.loginUserCode = HttpContextExtendBase.GetLoginCode();
      CommonResult result = await LogApplication.GetApplication(container).GetListc(query);
      return new JsonResult(result);
    }

    /// <summary>
    /// 登录日志导出数据信息
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpGet("ExportDataa"), AllowAnonymous]
    public async Task<IActionResult> ExportDataa([FromQuery] SigninInfo query)
    {
      return await Task.Factory.StartNew<IActionResult>(() =>
      {
        MemoryStream ms = new MemoryStream();
        var exportname = "登录日志信息统计";
        var filepath = "\\template\\report\\loginlog.xls";
        var tableName = TableAtributeUtil.GetTable<SigninInfo>();
        string sql = query.GetQueryString<SigninInfo>(null);
        var loginUserCode = HttpContextExtendBase.GetLoginCode(query.loginToken);
        var LoginAppid = HttpContextExtendBase.GetLoginAppid(query.loginToken);
        if (
          string.Compare("admin", LoginAppid, true) != 0
          && string.Compare(loginUserCode, "ajng", true) != 0
        )
        {
          sql += $" and logincode like '%{query.logincode}%' ";
        }
        else
        {
          if (!query.logincode.IsNull())
          {
            sql += $" and logincode like '%{query.logincode}%' ";
          }
        }
        sql += $" and cTime>= '{query.sttime}' and cTime<='{query.ettime}' ";
        SigninInfoQuery signinInfoQuery = new SigninInfoQuery()
        {
          tableName = tableName,
          sqlWhere = sql,
          sortFile = query.sortFile,
          sortType = query.sortType,
          pageIndex = query.pageIndex,
          pageSize = 100000,
          files = "*"
        };
        long total = 0;
        List<SigninInfo> list = new List<SigninInfo>();
        this.mySqlSugar.GetList<SigninInfo>(signinInfoQuery, out var msg, out list, out total);
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          string webRootPath = webHost.WebRootPath;
          string fileName = webRootPath + filepath;
          ms = LogExport.ExportDataa(fileName, exportname, list, out var msgb);
          if (string.IsNullOrEmpty(msg) && ms != null)
          {
            return File(ms.ToArray(), "application/ms-excel", exportname + ".xls");
          }
          else
          {
            return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
          }
        }
        else
        {
          return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
        }
      });
    }


    /// <summary>
    /// 控制器日志导出数据信息
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpGet("ExportDatab"), AllowAnonymous]
    public async Task<IActionResult> ExportDatab([FromQuery] Controllerexelog query)
    {
      return await Task.Factory.StartNew<IActionResult>(() =>
      {
        MemoryStream ms = new MemoryStream();
        var exportname = "控制器日志信息统计";
        var filepath = "\\template\\report\\controllerlog.xls";
        var tableName = TableAtributeUtil.GetTable<Controllerexelog>();
        string sql = query.GetQueryString<Controllerexelog>(null);
        var loginUserCode = HttpContextExtendBase.GetLoginCode(query.loginToken);
        var LoginAppid = HttpContextExtendBase.GetLoginAppid(query.loginToken);
        if (
          string.Compare("admin", LoginAppid, true) != 0
          && string.Compare(loginUserCode, "ajng", true) != 0
        )
        {
          sql += $" and ucode like '%{query.ucode}%' ";
        }
        else
        {
          if (!query.ucode.IsNull())
          {
            sql += $" and ucode like '%{query.ucode}%' ";
          }
        }
        sql += $" and cTime>= '{query.sttime}' and cTime<='{query.ettime}' ";
        ControllerexelogQuery controllerexelogQuery = new ControllerexelogQuery()
        {
          tableName = tableName,
          sqlWhere = sql,
          sortFile = query.sortFile,
          sortType = query.sortType,
          pageIndex = query.pageIndex,
          pageSize = 100000,
          files = "*"
        };
        long total = 0;
        List<Controllerexelog> list = new List<Controllerexelog>();
        this.mySqlSugar.GetList<Controllerexelog>(controllerexelogQuery, out var msg, out list, out total);
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          string webRootPath = webHost.WebRootPath;
          string fileName = webRootPath + filepath;
          ms = LogExport.ExportDatab(fileName, exportname, list, out var msgb);
          if (string.IsNullOrEmpty(msg) && ms != null)
          {
            return File(ms.ToArray(), "application/ms-excel", exportname + ".xls");
          }
          else
          {
            return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
          }
        }
        else
        {
          return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
        }
      });
    }


    /// <summary>
    /// 功能操作日志导出数据信息
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpGet("ExportDatac"), AllowAnonymous]
    public async Task<IActionResult> ExportDatac([FromQuery] Log query)
    {
      return await Task.Factory.StartNew<IActionResult>(() =>
      {
        MemoryStream ms = new MemoryStream();
        var exportname = "功能操作日志信息统计";
        var filepath = "\\template\\report\\operatelog.xls";
        var tableName = TableAtributeUtil.GetTable<Log>();
        string sql = query.GetQueryString<Log>(null);
        var loginUserCode = HttpContextExtendBase.GetLoginCode(query.loginToken);
        var LoginAppid = HttpContextExtendBase.GetLoginAppid(query.loginToken);
        if (
          string.Compare("admin", LoginAppid, true) != 0
          && string.Compare(loginUserCode, "ajng", true) != 0
        )
        {
          sql += $" and luser like '%{query.luser}%' ";
        }
        else
        {
          if (!query.luser.IsNull())
          {
            sql += $" and luser like '%{query.luser}%' ";
          }
        }
        sql += $" and cTime>= '{query.sttime}' and cTime<='{query.ettime}' ";
        LogQuery controllerexelogQuery = new LogQuery()
        {
          tableName = tableName,
          sqlWhere = sql,
          sortFile = query.sortFile,
          sortType = query.sortType,
          pageIndex = query.pageIndex,
          pageSize = 100000,
          files = "*"
        };
        long total = 0;
        List<Log> list = new List<Log>();
        this.mySqlSugar.GetList<Log>(controllerexelogQuery, out var msg, out list, out total);
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          string webRootPath = webHost.WebRootPath;
          string fileName = webRootPath + filepath;
          ms = LogExport.ExportDatac(fileName, exportname, list, out var msgb);
          if (string.IsNullOrEmpty(msg) && ms != null)
          {
            return File(ms.ToArray(), "application/ms-excel", exportname + ".xls");
          }
          else
          {
            return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
          }
        }
        else
        {
          return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
        }
      });
    }
  }
}
